#include <stdio.h>
#include <stdlib.h>
// windows下包含
#include <winsock2.h>
#include <inaddr.h>
#include <ws2tcpip.h>
// linux下使用
//#include <sys/socket.h>
//#include <netinet/in.h>

int make_socket(int port) {

    int sock;
    struct sockaddr_in name;

    // --- windows中创建socket需要先注册 --- start
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;
    wVersionRequested = MAKEWORD(1, 1);
    err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0) {
        printf(("\n\n-----TCP WSAStartup failed------\n\n"));
        return S_FALSE;
    }
    // windows 创建socket需要添加的代码 ---end

    // 创建字节流的IPV4 sock
    sock = socket(PF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        perror("socket error: ");
        exit(EXIT_FAILURE);
    }

    printf("socket创建完成, bind...ing...");

    // IPV4
    name.sin_family = AF_INET;
    // 指定端口
    name.sin_port = htons(port);
    // 通配地址
    name.sin_addr.S_un.S_addr = htonl(INADDR_ANY);

    int binder = bind(sock, (struct sockaddr *) &name, sizeof(name));

    if (binder < 0) {
        perror("bind error");
        exit(EXIT_FAILURE);
    }

    return sock;
}



int main() {

    // 创建socket
    int sock = make_socket(8000);

    // 进行监听
    int lis = listen(sock, 1024);

    printf("\n listen返回的值為: %d \n", lis);

    struct sockaddr cli_addr;
    int addr_len = sizeof(struct sockaddr_in);
//    int acc = accept(sock, &cli_addr, &addr_len);
    while (1) {
        int acc = accept(sock, &cli_addr, &addr_len);
        if(acc == -1){
            printf("接收失败");
        }else {
            printf("acc = %d,sock=%d,cli_addr=%s,addr_len=%d\n",
                   acc, sock, cli_addr, addr_len);
        }
//        read_data(sock);
        closesocket(sock);
    }
    return 0;
}